package ru.st.selenium.pages;

import static org.junit.Assert.*;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOf;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class FilmPage extends AnyPage {
	  private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();

	public FilmPage(PageManager pages) {
		super(pages);
	}
	
  public FilmPage ensurePageLoaded() {
    super.ensurePageLoaded();
    wait.until(visibilityOf(DeleteLink));
    return this;
  }
  
  @FindBy(css = "div.nocover")
  private WebElement NoCoverElement;
  
  @FindBy(css = "img[alt=\"Remove\"]")
  private WebElement DeleteLink;  
  
  public void deleteFilm() {
	  DeleteLink.click();
	    assertTrue(closeAlertAndGetItsText().matches("^Are you sure you want to remove this[\\s\\S]$"));
	    try {
	      assertEquals("No movies where found.", driver.findElement(By.cssSelector("div.content")).getText());
	    } catch (Error e) {
	      verificationErrors.append(e.toString());
	    }
	  }
  
  public void clickNoCover() {
	  NoCoverElement.click();
	  } 
  
  private String closeAlertAndGetItsText() {
	    try {
	      Alert alert = driver.switchTo().alert();
	      String alertText = alert.getText();
	      if (acceptNextAlert) {
	        alert.accept();
	      } else {
	        alert.dismiss();
	      }
	      return alertText;
	    } finally {
	      acceptNextAlert = true;
	    }
	  }
}